#!/usr/bin/env bash
set -euo pipefail

export AWS_PAGER=""

CLUSTER_NAME="terrateam-app"
SERVICE_NAME="terrateam-app-service"
IMAGE_NAME="terrat-ee"
GHCR_IMAGE="ghcr.io/${GITHUB_REPOSITORY_OWNER}/${IMAGE_NAME}:${VERSION_TAG}"

# Fetch the current service information
aws ecs describe-services --cluster "$CLUSTER_NAME" --services "$SERVICE_NAME" > service.json
TASK_DEF_ARN=$(jq -r '.services[0].taskDefinition' service.json)

# Fetch the current task definition
aws ecs describe-task-definition --task-definition "$TASK_DEF_ARN" > task-def.json

# Create the new task definition JSON
jq --arg newImage "$GHCR_IMAGE" '
  .taskDefinition |
  .containerDefinitions |= map(
    if .name == "app" then
      .image = $newImage
    else
      .
    end
  ) |
  del(.revision, .status, .taskDefinitionArn, .registeredBy, .registeredAt, .compatibilities, .requiresAttributes)
' task-def.json > task-def-updated.json

# Register the new task definition
NEW_TASK_DEF=$(aws ecs register-task-definition --cli-input-json file://task-def-updated.json)
NEW_TASK_DEF_ARN=$(echo "$NEW_TASK_DEF" | jq -r '.taskDefinition.taskDefinitionArn')

# Update the service to use the new task definition
aws ecs update-service --cluster "$CLUSTER_NAME" --service "$SERVICE_NAME" --task-definition "$NEW_TASK_DEF_ARN"

# Wait for the service to stabilize
aws ecs wait services-stable --cluster "$CLUSTER_NAME" --services "$SERVICE_NAME"

echo "Service updated successfully to task definition: $NEW_TASK_DEF_ARN"
